package com.yan.yjhTest.concurrency.thread.countDownLatch;
 
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
 
/**
 * ClassName:CountDownLatchTest <br/>
 * Function: TODO ADD FUNCTION. <br/>
 * Reason: TODO ADD REASON. <br/>
 * Date: 2015年7月30日 下午2:04:07 <br/>
 * 
 * @author chiwei
 * @version
 * @since JDK 1.6
 * @see
 */
public class CountDownLatchTest {
 
	public static void main(String[] args) {
		ThreadPoolExecutor poolExe = new ThreadPoolExecutor(100, 1000, 1, TimeUnit.SECONDS,
			    new LinkedBlockingDeque<Runnable>(100));
		// 考试开始铃声响起，考试开始
		final CountDownLatch examBegin = new CountDownLatch(1);
		// 单个考生，考试结束交卷
		final CountDownLatch student = new CountDownLatch(10);
 
		// 一个考场10位考生
		for (int i = 0; i < 10; i++) {
			Runnable runnable = new Runnable() {
				public void run() {
					try {
						System.out.println("考生" + Thread.currentThread().getName() + "在等待考试开始的铃声响起");
						examBegin.await();
						System.out.println("考生听到铃声" + Thread.currentThread().getName() + "开始答题");
						Thread.sleep((long) (Math.random() * 100));//答题过程，真正的业务逻辑处理部分
						System.out.println("考生" + Thread.currentThread().getName() + "交卷");
						student.countDown();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			};
			poolExe.execute(runnable); // 运动员开始任务
		}
 
		try {
			// 答题时间
			Thread.sleep((long) (Math.random() * 10000));
			System.out.println("考场" + Thread.currentThread().getName() + "开始铃声即将响起");
			examBegin.countDown(); // 命令计数器置为0
			System.out.println("考场" + Thread.currentThread().getName() + "考试开始铃声响起");
			student.await(); // 所有考生交卷
			System.out.println("考场" + Thread.currentThread().getName() + "考试结束");
		} catch (Exception e) {
			e.printStackTrace();
		}
		poolExe.shutdown();
 
	}
 
}
